from django.contrib import auth
from django.contrib.auth.decorators import login_required,user_passes_test
from django.contrib.auth.models import User
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import HttpResponseRedirect
from django.shortcuts import render,reverse
from .models import Book,Image

# Create your views here.
def index(request):
    context = {'active_menu':'homepage'}
    return render(request, 'management/index.html',context)

def sign_up(request):
    print(f"注册方法中的 request =========>{request}")
    state=''
    if request.user.is_authenticated:                   ## 使用 Django 自动去判断 是否登录
        return HttpResponseRedirect(reverse('homepage'))
    ### 判断用户的请求
    if request.method == 'POST':
        password = request.POST.get("password","")       ##  只是前端标签中的 name
        repeat_password = request.POST.get("repeat_password","")
        if password == '' or repeat_password == '':
            state = 'empty'                              ## 后端根据 state 去写不同的逻辑
        elif password != repeat_password:
            state = 'wrong'
        else:                                            ## 只剩下  password == repeat_password 一种情况了
            username = request.POST.get("username","")   ## 获取 表单中 提交上的 用户名
            if User.objects.filter(username=username):
                state = 'exist'
            else:
                user = User.objects.create_user(username=username,password=password,email=request.POST.get("email",""))
                user.save()
                state = 'success'

    context = {                                         ## 上下文 请求从视图传递给 模板
        'active_menu':'sign up',
        'state':state,                                  ## state的值 就这样传递给 模板引擎了
        'user': None
    }
    return render(request, 'management/sign_up.html',context)

def login(request):
    if request.user.is_authenticated: return HttpResponseRedirect(reverse('homepage'))
    context = {'active_menu': 'login'}
    state =''
    if request.method == 'POST':
        username = request.POST.get("username","")
        password = request.POST.get('password',"")
        user =auth.authenticate(username=username,password=password)
        print(f"user is ======{user}")
        if user is not None:
            auth.login(request,user)
            target_url = request.GET.get('next',reverse('homepage'))  ## 获取 next 没有默认是 反转到 homepage
            print(f"target_url is ======: {target_url}")
            return HttpResponseRedirect(target_url)
        else:
            state = 'wrong'
        context = {
            'active_menu':'homepage',
            'state':state,
            'user':None
        }
    print(f"context is {context}")
    return render(request,"management/login.html",context)


def logout(request):
    auth.logout(request)
    return HttpResponseRedirect(reverse('homepage'))

##只有登录的用户才能修改密码
@login_required
def  change_password(request):
    user = request.user
    print(f" user is {user}")
    print(f" change_password is {user.password}")
    state = ""
    ## 获取post 数据
    old_password = request.POST.get('old_password',"")
    new_password = request.POST.get('new_password',"")
    repeat_password = request.POST.get('repeat_password',"")

    print(f"old_password is {user.check_password(old_password)}")
    if user.check_password(old_password):
        if not new_password:
            state = 'empty'
        elif repeat_password != new_password:
            state = 'repeat_error'
        elif repeat_password == "" or new_password == "":
            state = 'empty'
        else:
            user.set_password(new_password)
            user.save()
            print(f"change password is {new_password}")
            state = 'success'
    else:
        state = 'password_error'
    ## 这里直接返回 这个 前端 根据 user、state 去做判断
    content = {
        'user':user,
        'active_menu':'homepage',
        'state':state
    }

    return render(request,"management/change_password.html",content)


@user_passes_test(lambda user: user.is_staff)
def add_book(request):
    user = request.user
    state = ""
    ## POST 提交表单
    if request.method == 'POST':
        new_book = Book(
            name=request.POST['name'],
            author=request.POST['author'],
            category=request.POST['category'],
            price=request.POST['price'],
            publish_date=request.POST['publish_date']
        )
        new_book.save()
        state = 'success'
    context = {
        "user":user,
        "state":state,
        "active_menu":"add_book"
    }
    return render(request,"management/add_book.html",context)


#@user_passes_test(lambda user: user.is_staff)
def add_img(request):
    user = request.user
    state = ""
    try:
        if request.method == 'POST':
            ##1、获取数据
            name = request.POST.get("name","").strip()
            description = request.POST.get("description","").strip()
            book = request.POST.get("book","").strip()
            img = request.FILES.get('img')

            ##2、后端数据校验
            if not name:
                raise ValueError("图片名称不能为空")
            if not book:
                raise ValueError("请选择书籍")


            new_img = Image(
                name=name,
                description=description,
                img=img,
                book=Book.objects.get(pk=request.POST.get('book', ""))  ## 这样做的目的是 判断这本书 存不存在
            )
            new_img.save()
            state = 'success'
    except ValueError as e:
        state = 'error'
        print(f"参数校验失败：{e}")
    except Book.DoesNotExist as e:
        state = 'error'
        print(f"上传图片异常========{e}")
    except Exception as e:
        state = 'error'
        print(f"保存失败：{e}")

    context = {
        "user": user,
        "state": state,
        "active_menu": "add_img",
        "book_list": Book.objects.all()
    }
    return render(request, "management/add_img.html", context)


@login_required
def book_list(request,category="all"):  ## category="all" 默认显示所有的分类
    user = request.user
    ## select distict category from book
    category_list = Book.objects.values_list('category', flat=True).distinct().order_by('category')
    ## 验证并处理分类参数
    if category != 'all' and category not in category_list:
        category = 'all'
    if category == 'all':
        books = Book.objects.all()
    else:
        books = Book.objects.filter(category=category)
    ## 按出版日期排序
    books  = books.order_by('-publish_date','name')


    ## 分页处理
    paginator = Paginator(books,5) ## 每页 5 本
    page = request.GET.get('page',1)         ## 默认第一页

    try:
        books = paginator.page(page)
    except PageNotAnInteger :
        books = paginator.page(1)
    except EmptyPage:
        books = paginator.page(paginator.num_pages)

    context = {
        "user":user,
        'active_menu': 'book_list',   ## 告诉 base.html 目前使用的哪个页面 高亮显示
        'category_list': category_list,
        'query_category':category,
        'book_list': books,
    }

    return render(request,'management/book_list.html', context)


@login_required
def book_detail(request,book_id=None):
    user = request.user
    print(f"book_id is {book_id}")

    if book_id is None:
        return HttpResponseRedirect(reverse('book_list',kwargs={'category':'all'}))
    try:
        book_id = int(book_id)
        book = Book.objects.get(pk=book_id)
    except Book.DoesNotExist:
        return HttpResponseRedirect(reverse('book_list',kwargs={'category':'all'}))

    context = {
        "user":user,
        "active_menu": "book_list",
        'book':book,
    }
    return render(request,"management/book_detail.html", context)